package model.data.container;

/**
 * CategoryContainer.java
 * Purpose: A container to hold category objects.
 * 
 * @author Jan Harm Van Enk
 * @version 0.1 12/01/2012
 */

import java.util.ArrayList;
import java.util.List;

import model.Category;
import model.data.CategoryStore;
import model.data.DuplicateRecordException;
import model.data.RecordNotFoundException;

public class CategoryContainer implements CategoryStore {
	/* List of categories */
	private ArrayList<Category> categories;
	
	/** Constructs a new category container */
	public CategoryContainer() {
		this.categories = new ArrayList<Category>();
	}
	
	/** Writes a category to the container */
	@Override
	public void write(Category category) throws DuplicateRecordException {
		if (this.getById(category.getId()) == null) {
			this.categories.add(category);
		}
		else
		{
			throw new DuplicateRecordException();
		}
	}
	
	/** Updates an existing category in the container */
	@Override
	public void update (Category category) {
		// TODO update logic
		// currently impossible due to referencing issue
	}
	
	/** Deletes an existing category from the container */
	@Override
	public void delete(Category category) throws RecordNotFoundException {
		if (this.getById(category.getId()) != null) {
			this.categories.remove(category);
		}
		else
		{
			throw new RecordNotFoundException();
		}
	}
	
	/** Returns the number of categories in the container */
	@Override
	public int getCount() {
		return this.categories.size();
	}
	
	/** Returns a category from the container with a specific id */
	@Override
	public List<Category> getById(long id) {
		ArrayList<Category> categories;
		
		// Create list
		categories = new ArrayList<Category>();
		
		// Fill list
		for (Category category : this.categories){
			if (category.getId() == id) {
				categories.add(category);
			}
		}
		
		// Return results
		return categories;
	}
	
	/** Returns an category from the container with a specific user name */
	@Override
	public List<Category> getByName(String name) {
		ArrayList<Category> categories;
		
		// Create list
		categories = new ArrayList<Category>();
		
		// Fill list
		for (Category category : this.categories){
			if (category.getName().equals(name)) {
				categories.add(category);
			}
		}
		
		// Return results
		return categories;
	}
}
